package itsen.com.bduidemo.modle.md.al2;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;

import butterknife.BindView;
import butterknife.ButterKnife;
import itsen.com.bduidemo.R;
import itsen.com.bduidemo.lib.util.ActivityAnimUtil;

public class Al2Activity extends AppCompatActivity {

    @BindView(R.id.btn_close)
    ImageButton btnClose;
    @BindView(R.id.iv_ad)
    ImageView ivAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_al2);
        ButterKnife.bind(this);
        ivAd.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                startAnim(ivAd,500);
            }
        });
    }

    private void startAnim(View view,int time){
        ObjectAnimator animator = ObjectAnimator.ofFloat(view,"translationY",-view.getHeight(),0);
        animator.setInterpolator(new OvershootInterpolator());
        animator.setDuration(time);
        animator.start();
    }

    private void startExitAnim(View view, final View btn){
        ObjectAnimator animator = ObjectAnimator.ofFloat(view,"translationY",0,-view.getHeight());
        animator.setDuration(500);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                finish();
                ActivityAnimUtil.startAnim(Al2Activity.this);
            }
        });
        animator.start();

        ObjectAnimator btnAnimator = ObjectAnimator.ofFloat(btn,"translationX",0,4*btn.getWidth());
        btnAnimator.setDuration(500);
        btnAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
               float rotaion = (float) animation.getAnimatedValue();
               // Log.e("rotaion",""+rotaion);
                rotaion = rotaion/(4*btn.getWidth());
                btn.setRotation(360*rotaion);
                btn.setAlpha(1-rotaion);

            }
        });
        btnAnimator.start();
    }

    public void close(View view){
       startExitAnim(ivAd,btnClose);
    }
    @Override
    public void onBackPressed() {

    }
}
